package com.synergy.stockflow.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.synergy.stockflow.annotation.Log;
import com.synergy.stockflow.annotation.LogModule;
import com.synergy.stockflow.entity.SysRole;
import com.synergy.stockflow.entity.SysUser;
import com.synergy.stockflow.entity.SysUserRole;
import com.synergy.stockflow.entity.dto.SysUserDTO;
import com.synergy.stockflow.entity.dto.SysUserPwdDTO;
import com.synergy.stockflow.entity.vo.QuerySysUserVO;
import com.synergy.stockflow.entity.vo.SysUserVO;
import com.synergy.stockflow.model.Result;
import com.synergy.stockflow.service.SysRoleService;
import com.synergy.stockflow.service.SysUserRoleService;
import com.synergy.stockflow.service.SysUserService;
import com.synergy.stockflow.utils.ConvertUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;

import javax.annotation.security.RolesAllowed;
import java.util.List;
import java.util.stream.Collectors;

@Tag(name = "系统用户", description = "对用户进行CRUD操作")
@RestController
@RequestMapping("/system/user")
@RolesAllowed({"ROLE_ADMIN", "ROLE_USER"})
@LogModule(name = "用户管理")
public class SysUserController {
    private final SysUserService sysUserService;

    private final SysRoleService sysRoleService;

    private final SysUserRoleService sysUserRoleService;


    @Autowired
    public SysUserController(SysUserService sysUserService, SysRoleService sysRoleService, SysUserRoleService sysUserRoleService) {
        this.sysUserService = sysUserService;
        this.sysRoleService = sysRoleService;
        this.sysUserRoleService = sysUserRoleService;
    }

    @PostMapping
    public Result<List<SysUserVO>> list(@RequestBody(required = false) QuerySysUserVO querySysUserVO) {
        return null;
    }

    @PostMapping("/list")
    @Log(title = "查询用户列表")
    public Result<Page<SysUserVO>> page(@RequestBody QuerySysUserVO querySysUserVO) {
        Page<SysUser> page = new Page<>(querySysUserVO.getCurrent(), querySysUserVO.getSize());
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        if (querySysUserVO.getGender() != null) queryWrapper.eq(SysUser::getGender, querySysUserVO.getGender());
        if (querySysUserVO.getStatus() != null) queryWrapper.eq(SysUser::getStatus, querySysUserVO.getStatus());
        if (querySysUserVO.getDelFlag() != null) queryWrapper.eq(SysUser::getDelFlag, querySysUserVO.getDelFlag());
        if (querySysUserVO.getUsername() != null && !querySysUserVO.getUsername().isEmpty())
            queryWrapper.like(SysUser::getUsername, querySysUserVO.getUsername()).or().like(SysUser::getNickname, querySysUserVO.getUsername());
        queryWrapper.ne(SysUser::getUsername, "admin");
        if (querySysUserVO.getRoleCodes() != null && !querySysUserVO.getRoleCodes().isEmpty()) {
            LambdaQueryWrapper<SysRole> roleQueryWrapper = new LambdaQueryWrapper<>();
            roleQueryWrapper.in(SysRole::getRoleCode, querySysUserVO.getRoleCodes());
            List<SysRole> sysRoles = sysRoleService.list(roleQueryWrapper);
            List<Integer> roleIds = sysRoles.stream().map(SysRole::getRoleId).collect(Collectors.toList());
            LambdaQueryWrapper<SysUserRole> userRoleQueryWrapper = new LambdaQueryWrapper<>();
            userRoleQueryWrapper.in(SysUserRole::getSysRoleId, roleIds);
            List<SysUserRole> userRoles = sysUserRoleService.list(userRoleQueryWrapper);
            List<Long> userIds = userRoles.stream().map(SysUserRole::getSysUserId).collect(Collectors.toList());
            if (!userIds.isEmpty()) {
                queryWrapper.in(SysUser::getId, userIds);
            } else {
                return Result.success(ConvertUtils.toPage(page, SysUserVO::fromEntity));
            }
        }
        queryWrapper.orderByDesc(SysUser::getCreateTime);
        Page<SysUserVO> voPage = ConvertUtils.toPage(sysUserService.page(page, queryWrapper), SysUserVO::fromEntity);

        return Result.success(voPage);
    }

    @PostMapping("/{username}")
    @Log(title = "根据用户名查询用户")
    public Result<SysUserVO> info(@PathVariable String username) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername, username);
        SysUser sysUser = sysUserService.getOne(queryWrapper);
        SysUserVO vo = ConvertUtils.copy(sysUser, SysUserVO.class);
        LambdaQueryWrapper<SysUserRole> userRoleQueryWrapper = new LambdaQueryWrapper<>();
        userRoleQueryWrapper.eq(SysUserRole::getSysUserId, sysUser.getId());
        List<SysUserRole> list = sysUserRoleService.list(userRoleQueryWrapper);
        if (list != null && !list.isEmpty()) {
            List<Integer> roleIdList = list.stream().map(SysUserRole::getSysRoleId).collect(Collectors.toList());
            LambdaQueryWrapper<SysRole> roleQueryWrapper = new LambdaQueryWrapper<>();
            roleQueryWrapper.in(SysRole::getRoleId, roleIdList);
            List<SysRole> sysRoles = sysRoleService.list(roleQueryWrapper);
            vo.setRoles(sysRoles);
        }
        return Result.success(vo);
    }

    @PutMapping("/status_update")
    @Log(title = "更新用户状态")
    @CacheEvict(cacheNames = {"auth", "permission"}, allEntries = true)
    public Result<Integer> updateUserStatus(@RequestBody SysUserVO vo) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        SysUser sysUser = sysUserService.getOne(queryWrapper.eq(SysUser::getId, vo.getId()));
        sysUser.setStatus(vo.getStatus());
        UpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<>();
        boolean updated = sysUserService.update(sysUser, updateWrapper.eq("id", sysUser.getId()));
        return Result.success(updated ? 1 : 0);
    }

    @PutMapping("/del_flag_update")
    @Log(title = "逻辑删除用户")
    @CacheEvict(cacheNames = {"auth", "permission"}, allEntries = true)
    public Result<Integer> updateDelFlag(@RequestBody SysUserVO vo) {
        return Result.success(sysUserService.updateUserDelFlag(vo));
    }

    @PutMapping("/del_flag_batch_update")
    @Log(title = "逻辑批量删除用户")
    @CacheEvict(cacheNames = {"auth", "permission"}, allEntries = true)
    public Result<Integer> updateBatchDelFlag(@RequestBody List<Long> ids) {
        return Result.success(sysUserService.updateBatchUserDelFlag(ids));
    }

    @PostMapping("/profile")
    @Operation(description = "查询当前登录用户")
    @Log(title = "查询当前登陆用户")
    public Result<SysUserVO> profile() {
        return Result.success(sysUserService.currentUser());
    }

    @PostMapping("/save_user")
    @Log(title = "添加用户")
    @CacheEvict(cacheNames = {"auth", "permission"}, allEntries = true)
    public Result<Boolean> saveUser(@RequestBody SysUserDTO dto) {
        return Result.success(sysUserService.saveUser(dto));
    }

    @PostMapping("/update_user")
    @Log(title = "修改用户信息")
    @CacheEvict(cacheNames = {"auth", "permission"}, allEntries = true)
    public Result<Boolean> updateUser(@RequestBody SysUserDTO dto) {
        return Result.success(sysUserService.updateUserByUsername(dto));
    }

    @PostMapping("/updatePwd")
    @Log(title = "根据用户名修改密码")
    @Operation(description = "修改用户密码")
    @CacheEvict(cacheNames = {"auth", "permission"}, allEntries = true)
    public Result<Boolean> updatePwd(@RequestBody SysUserPwdDTO dto) {
        return Result.success(sysUserService.updatePwdByUsername(dto));
    }

    @PostMapping("/updateBasic")
    @Log(title = "根据用户名修改用户基本信息")
    @Operation(description = "修改基本信息")
    @CacheEvict(cacheNames = {"auth", "permission"}, allEntries = true)
    public Result<Boolean> updateBasic(@RequestBody SysUserDTO dto) {
        return Result.success(sysUserService.updateUserInfoByUsername(dto));
    }
}
